package com.jzg.jcptadmin.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.adpter.ChooseAdapter;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CharacterParser;
import com.jzg.jcptadmin.data.vo.PinyinComparator;
import com.jzg.jcptadmin.data.vo.SourceData;
import com.jzg.jcptadmin.presenter.SourcePresenter;
import com.jzg.jcptadmin.view.SideBar;
import com.jzg.jcptadmin.viewinterface.SourceInterface;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by jzg on 2015/12/28.
 * 颜色、车源机构选择界面
 */
public class ChooseActivity extends BaseActivity implements SourceInterface {

    @Bind(R.id.tv_content)
    TextView tvTitle;
    @Bind(R.id.lv_listchoose)
    ListView lvListchoose;
    @Bind(R.id.loading)
    ViewStub loading;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private ChooseAdapter adapter;
    private String[] data;
    private SourceData datas;
    private List<SourceData.TableEntity> lists = new ArrayList<>();
    private String state;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_activity);
        ButterKnife.bind(this);
        data = getIntent().getStringArrayExtra(Constant.CHOOSE_ITEM);
        state = getIntent().getStringExtra(Constant.CHOOSE_STATE);
        if (data == null && state != null) {
            SourcePresenter areaPresenter = new SourcePresenter(DataManager.getInstance());
            areaPresenter.attachView(this);
            areaPresenter.LoadSourceData(state,appContext.getUser().getUserId()+"");
        }
        tvTitle.setText("请选择车源机构");
        int requestCode = getIntent().getIntExtra(Constant.INPUT_REQUESTCODE, 0);
        String title = getIntent().getStringExtra(Constant.INPUT_TITLE);
        if (title != null) {
            tvTitle.setText(title);
        }

        initViews();


    }

    private void initViews() {
        adapter = new ChooseAdapter(this, lists);//初始化adapter
        loading.setVisibility(View.VISIBLE);//显示进度条
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        //pinyinComparator1 = new PinyinComparator1();

        SideBar sideBar = (SideBar) findViewById(R.id.sidrbar);
        TextView dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    lvListchoose.setSelection(position);
                }
            }
        });

        lvListchoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
                //Toast.makeText(ChooseActivity.this, ((ChooseBean) adapter.getItem(position)).getChooseitem(), Toast.LENGTH_SHORT).show();

                Intent intent = new Intent();
                intent.putExtra(Constant.ACTIVITY_CHOOSE, ((SourceData.TableEntity) adapter.getItem(position)).getName());
                if (data == null && state != null) {

                    intent.putExtra(Constant.ACTIVITY_SOURCEID, ((SourceData.TableEntity) adapter.getItem(position)).getId());
                }
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        if (data != null) {
            lists = filledData(data);
            Collections.sort(lists, pinyinComparator);
            if(adapter==null){
                adapter = new ChooseAdapter(this, lists);
            }else{
                adapter.UpData(lists);
            }
            lvListchoose.setAdapter(adapter);
            adapter.notifyDataSetChanged();
          //  loading.setVisibility(View.GONE);//隐藏进度条
        } else {
          /*   lists = filledData(datas);
            Collections.sort(lists, pinyinComparator);
           adapter = new ChooseAdapter(this,lists);
            lvListchoose.setAdapter(adapter);*/
        }
        // 根据a-z进行排序源数据
    }

    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<SourceData.TableEntity> filledData(String[] data) {
        List<SourceData.TableEntity> mSortList = new ArrayList<SourceData.TableEntity>();
        for (int i = 0; i < data.length; i++) {
            SourceData.TableEntity bean = new SourceData.TableEntity();
            bean.setName(data[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(data[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                bean.setSortLetters(sortString.toUpperCase());
            } else {
                bean.setSortLetters("#");
            }
            mSortList.add(bean);
        }
        return mSortList;

    }

    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<SourceData.TableEntity> filledData(SourceData datas) {
        List <SourceData.TableEntity>listdata = new ArrayList<SourceData.TableEntity>();
        List<SourceData.TableEntity> list = datas.getTable();
        for (int i = 0; i < list.size(); i++) {
          /*  ChooseBean bean = new ChooseBean();
            bean.setChooseitem(data[i]);*/
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(list.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                list.get(i).setSortLetters(sortString.toUpperCase());
            } else {
                list.get(i).setSortLetters("#");
            }
            listdata.add(list.get(i));
        }
        return listdata;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    @Override
    public void showDatas(SourceData datas) {
        //loading.setVisibility(View.GONE);//隐藏进度条
        if(Constant.SUCCESS ==datas.getStatus()){
            this.datas = datas;
            lists = filledData(datas);
            Collections.sort(lists, pinyinComparator);
            if(adapter==null){
                adapter = new ChooseAdapter(this, lists);
            }else{
                adapter.UpData(lists);
            }
            lvListchoose.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }else {

            Toast.makeText(ChooseActivity.this, datas.getMsg(), Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void showError(String error) {

        Toast.makeText(this, Constant.errr_net, Toast.LENGTH_SHORT).show();
    }
}
